<template>
    <div>
      <a-row :gutter="24">
        <a-col :xl="6" :style="{ marginBottom: '24px' }" v-for="(item,index) in totalArr" :key="index">
          <chart-card :title="item.title" :total="item.value"></chart-card>
        </a-col>
      </a-row>
      <div class="warpper-box">
         <form-create 
        v-model="params.fApi" 
        :rule="params.rule" 
        :option="params.option" 
        @btn-search-click="loadTable(true)"
        @btn-reset-click="reset"/>
        <div style="margin-bottom: 20px;">
            <a-button icon="file-excel" v-action:signExportExcelBtn @click="down('excel','导出')" type="primary">导出excel文件</a-button>
            <a-button icon="file-zip" v-action:signDownContractBtn @click="down('contract','下载')" type="primary">批量合同下载</a-button>
            <a-button type="primary" v-action:signImportIdcardBtn icon="idcard" @click="$refs.createIdentity.add();">导入身份证</a-button>
            <a-button type="primary" v-action:signImportContractBtn icon="file-pdf" @click="$refs.createContract.add();">导入线下协议</a-button>
            <a-button type="primary" v-action:signQrcodeAddBtn icon="qrcode" @click="$refs.createQrcodeAdd.add();">生成签约二维码</a-button>
             <a-button type="danger" v-action:signAddBtn @click="addSign" icon="plus">新增</a-button>
        </div>
        <a-table 
        :columns="table.columns" 
        :pagination="table.pagination" 
        @change="handleTableChange" 
        :rowKey="(record,index)=>{return index}"
        :data-source="table.loadData" 
        :scroll="{ x: 2200 }">
            <span slot="action" slot-scope="text, record">
                <a @click="$refs.createSignDetail.add(record)">详情</a>
                <a-popconfirm
                    :title="'是否删除'+`${record.name} `+'？'"
                    ok-text="确认"
                    cancel-text="取消"
                    @confirm="signDel(record)" >
                    <a-divider v-action:signDelBtn type="vertical" />
                    <a v-action:signDelBtn>删除</a>
                </a-popconfirm>
            </span>
            <span slot="idCard" slot-scope="text, record">
              <a-popover title="身份证号码" trigger="hover">
                <template #content>
                <p style="margin: 0;">{{record.idCard}}</p>
                </template>
                <a-button style="padding: 0;color:#000" type="link">{{record.idCard | filterMore(7)}}</a-button>
              </a-popover>
            </span>
            <span slot="phone" slot-scope="text, record">
              <a-popover title="手机号码" trigger="hover">
                <template #content>
                <p style="margin: 0;">{{record.phone}}</p>
                </template>
                <a-button style="padding: 0;color:#000" type="link">{{record.phone | filterMore(7)}}</a-button>
              </a-popover>
            </span>
            <span slot="enterName" slot-scope="text, record">
              <a-popover title="企业名称" trigger="hover">
                <template #content>
                <p style="margin: 0;">{{record.enterName}}</p>
                </template>
                <a-button style="padding: 0;color:#000" type="link">{{record.enterName | filterMore(5)}}</a-button>
              </a-popover>
            </span>
            <span slot="soueceName" slot-scope="text, record">
              <a-popover title="签约方" trigger="hover">
                <template #content>
                <p style="margin: 0;">{{record.soueceName}}</p>
                </template>
                <a-button style="padding: 0;color:#000" type="link">{{record.soueceName | filterMore(5)}}</a-button>
              </a-popover>
            </span>
            <span slot="parkName" slot-scope="text, record">
              <a-popover title="签约园区名称" trigger="hover">
                <template #content>
                <p style="margin: 0;">{{record.parkName}}</p>
                </template>
                <a-button style="padding: 0;color:#000" type="link">{{record.parkName | filterMore(7)}}</a-button>
              </a-popover>
            </span>
            <span slot="fileUrl" slot-scope="text, record">
                <a-button type="link" v-if="record.fileUrl" @click="previewClick(record.fileUrl)">预览</a-button>
            </span>
             <span slot="pactUrl" slot-scope="text, record">
                <a-button type="link" v-if="record.pactUrl" @click="previewClick(record.pactUrl)">预览</a-button>
            </span>
            <span slot="idCardFront" slot-scope="text, record">
              <template v-if="record.idCardFront || record.idCardReverse">
                <viewer :images="[record.idCardFront,record.idCardReverse]">
                  <img :src="record.idCardFront" style="width:50px;height:50px;cursor: pointer;margin:4px;">
                  <img :src="record.idCardReverse" style="width:50px;height:50px;cursor: pointer;margin:4px;">
                </viewer>
              </template>
            </span>
            
        </a-table>
      </div>
      <enterprise-sign-add ref="createEnterpriseSignAdd" @on-ok="loadTable(true)"/>
      <park-sign-add ref="createParkSignAdd" @on-ok="loadTable(true)"/>
      <user-sign-detail ref="createSignDetail"/>
      <identity-upload ref="createIdentity" @on-ok="loadTable(true)"/>
      <contract-upload ref="createContract" @on-ok="loadTable(true)"/>
      <qrcode-add ref="createQrcodeAdd"/>
      <a-modal :title="options.title" :width="400" 
      :visible="options.visible"
       :confirmLoading="options.submitLoading"  
       @ok="handleFileOk"
       @cancel="options.visible=false">
          <p>{{options.text}}</p>
      </a-modal>
    </div>
</template>

<script>
import { mapGetters,mapActions } from 'vuex'
import store from '@/store'
import { previewAFile,xlsx } from '@/utils/util'
import moment from 'moment';
import { ChartCard } from '@/components'
import { 
  allGetSignList,
  allSignDel
 } from '@/api/manage/sign'
import 
  enterpriseSignAdd
from './enterprise_sign_add'
import 
  parkSignAdd
from './park_sign_add'
import 
  UserSignDetail
from './user_sign_detail'
import 
  IdentityUpload
from './identity_upload'
import 
  ContractUpload
from './contract_upload'
import 
  QrcodeAdd
from './qrcode_add'
import {
  PARAMS_SIGN,
  COLUMNS_SIGN,
  OPTION_BLOCK,
  OPTION_INLINE
} from './form'
import QRCode from 'qrcodejs2'
import 'moment/locale/zh-cn'
export default {
  name: 'sign',
  components: {
    ChartCard,
    enterpriseSignAdd,
    parkSignAdd,
    UserSignDetail,
    IdentityUpload,
    ContractUpload,
    QrcodeAdd
  },
  data () {
    return {
      totalArr:[
        {value:0,title:'已签约',filed:'succeeTotal'},
        {value:0,title:'未签约',filed:'noneTotal'},
        {value:0,title:'即将到期',filed:'awayTotal'},
        {value:0,title:'到期',filed:'pastTotal'}
      ],
      params:{
        fApi:{},
        rule:PARAMS_SIGN,
        option:OPTION_INLINE
      },
      table:{
        columns:[],
        loadData:[],
        pagination:{
          current:1,
          total:0,
          pageSize: 10,
          showSizeChanger: true,
					showQuickJumper: true,
          pageSizeOptions: ["10", "20", "50", "100"],
          showTotal: total => `共有 ${total} 条数据`,
        }
      },
      options:{
        submitLoading:false,
        state:'',
        title:'',
        text:'',
        visible:false
      }
    }
  },
  filters: {
    filterMore (value,num) {
      if (!value) return ''
      if (value.length > num) {
          return value.slice(0,num) + '...'
      }
      return value
    }
  },
  computed: {
    ...mapGetters(['userInfo'])
  },
  created () {
    if(this.userInfo.type === 2){
        this.$nextTick(()=>{
          this.params.fApi.updateRules({'source':{title:'园区公司'}},true);
          this.params.fApi.hidden(false,'add');
          this.params.fApi.hidden(true,'enterpriseName');
        })
      }else if(this.userInfo.type === 3){
        this.$nextTick(()=>{
          this.params.fApi.updateRules({'source':{title:'企业公司'}},true);
          this.params.fApi.hidden(false,'add');
          this.params.fApi.hidden(true,'enterpriseName');
        })
      }else if(this.userInfo.type === 1){
        this.$nextTick(()=>{
          this.params.fApi.updateRules({'source':{title:'园区公司'}},true);
          this.params.fApi.hidden(true,'add');
          this.params.fApi.hidden(false,'enterpriseName');
        })
      }
      this.generateRoutes();
      this.initData();
  },
  methods: {
     ...mapActions({
      generateRoutes:'generateRoutes'
    }),
    initData(){
      let signKey = this.userInfo.roleFiledAuthorities.signKey;
      if(signKey && signKey.length >= 1){
        this.table.columns = COLUMNS_SIGN.filter(v=> !signKey.includes(v.dataIndex));
      }else{
         this.table.columns = COLUMNS_SIGN;
      }
      this.loadTable(true);
    },
    async loadTable(flag){
      let params = {};
      if(JSON.stringify(this.params.fApi) !== "{}"){
        const formData = this.params.fApi.formData();
        params.name = formData.name;
        params.state = formData.state;
        params.type = formData.type;
        params.idCard = formData.idCard;
        params.hasidCar = formData.hasidCar;
        params.expire = formData.expire;
        params.phone = formData.phone;
        params.source = formData.source;
        params.enterpriseName = formData.enterpriseName;
        params.startTime = formData.day[0];
        params.endTime = formData.day[1];
      }
      if(flag){
        this.table.pagination.current = 1;
        this.table.pagination.pageSize = 10;
      }
      params.pageNum = this.table.pagination.current;
      params.pageSize = this.table.pagination.pageSize;
      const {code,data,noneTotal,awayTotal,succeeTotal,pastTotal} = await allGetSignList(params);
      if(code ==='1'){
        this.table.loadData = data.content;
        this.table.pagination.total = data.total || 0;
        this.totalArr.forEach(v => {
            if(v.filed.indexOf('noneTotal') !== -1){
              v.value = noneTotal;
            }else if(v.filed.indexOf('pastTotal') !== -1){
              v.value = pastTotal;
            }else if(v.filed.indexOf('succeeTotal') !== -1){
              v.value = succeeTotal;
            }else if(v.filed.indexOf('awayTotal') !== -1){
              v.value = awayTotal;
            }
        });
      }
    },
    handleTableChange(pagination){
      this.table.pagination.current = pagination.current;
      this.table.pagination.pageSize = pagination.pageSize;
      this.loadTable(false);
    },
    previewClick(fileUrl){
      previewAFile(fileUrl);
    },
    down(type,text){
      this.options.state = type;
      this.options.title = type == 'excel' ?'导出excel':'下载合同';
      this.options.text = type == 'excel' ?'可筛选条件导出':'只能下载当前页的数据，在右下角分页处可以调整每页条数 最多100条';
      this.options.visible = true;
      this.options.submitLoading = false;
    },
    async handleFileOk(){
      let params = {};
      if(JSON.stringify(this.params.fApi) !== "{}"){
        const formData = this.params.fApi.formData();
        params.name = formData.name;
        params.state = formData.state;
        params.type = formData.type;
        params.idCard = formData.idCard;
        params.hasidCar = formData.hasidCar;
        params.phone = formData.phone;
        params.source = formData.source;
        params.enterpriseName = formData.enterpriseName;
        params.startTime = formData.day[0];
        params.endTime = formData.day[1];
      }
      this.options.submitLoading = true;
      if(this.options.state === 'excel'){
         params.pageNum = 1;
        params.pageSize = this.table.pagination.total;
        const {code,data} = await allGetSignList(params);
         this.options.submitLoading = false;
        if(code ==='1'){
          if(data.content && data.content.length > 0){
            let fields = {
              title0: "序号",
              title1: "姓名",
              title2: "签约企业",
              title3: "身份证号",
              title4: "手机号码",
              title5: "签约方式",
              title6: "签约状态",
              title7: "实名认证",
              title8: "签约日期"
            };
            let arry = [];
            let i = 0;
            data.content.forEach(ele => {
                i++;
                let signTypeText = '';
               if (ele.type === 2){
                    signTypeText = '短信签约'
                } else if (ele.type === 3){
                    signTypeText = '小程序签约'
                } else if (ele.type === 4){
                    signTypeText = '线下签约'
                }
                let idCardFrontText = '';
                 if (ele.idCardFront) {
                    idCardFrontText = '已小程序实名认证'
                } else{
                    idCardFrontText = '已短信实名认证'
                }
                let sginStatusText = '';
                if (ele.status === 1) {
                    sginStatusText = '未签约'
                } else if (ele.status === 2){
                    sginStatusText = '已签约'
                } else if (ele.status === 3){
                    sginStatusText = '待签约'
                } else if (ele.status === 4){
                    sginStatusText = '签约失败'
                }
                arry.push({
                    title0: i,
                    title1: ele.name,
                    title2: ele.enterName,
                    title3: ele.idCard,
                    title4: ele.phone,
                    title5: signTypeText,
                    title6: sginStatusText,
                    title7: idCardFrontText,
                    title8: ele.signedTime ? ele.signedTime : ''
                });
            });
            let wscols = [
                { wch: 10 },
                { wch: 15 },
                { wch: 40 },
                { wch: 30 },
                { wch: 20 },
                { wch: 15 },
                { wch: 15 },
                { wch: 25 },
                { wch: 25 },
            ];
            xlsx(arry, fields,wscols, "签约列表");
             this.options.visible = false;
          }else{
            this.$message.error('没有可导数据');
          }
        }
      }else{
        const result = await store.dispatch('allSginDownContract',this.table.loadData);
        if(result){
          this.options.submitLoading = false;
          this.options.visible = false;
        }else{
          this.$message.error('没有下载合同');
        }
      }
      
    },
    addSign(){
      if(this.userInfo.type === 2){
        this.$refs.createEnterpriseSignAdd.add();
      }else if(this.userInfo.type === 3){
         this.$refs.createParkSignAdd.add()
      }
    },
    async signDel(item){
      let params = {id:item.id};
      const {code} = await allSignDel(params);
      if(code === '1'){
        this.$message.success('操作成功');
        this.loadTable(false);
      }
    },
    reset(){
      this.params.fApi.resetFields();
      this.loadTable(true);
    }
  }
}
</script>


